package com.internetCafes.spms.core.utils;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Spring Context 工具类
 * 
 * @author Sunny
 * @email rekeeper2011@hotmail.com
 * @date 2016年11月29日 下午11:45:51
 */
@Component
public class SpringContextUtils implements ApplicationContextAware {
	public static ApplicationContext applicationContext; 

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		SpringContextUtils.applicationContext = applicationContext;
	}

	public static <T> T getBean(String name, Class<T> requiredType) {
		return applicationContext.getBean(name, requiredType);
	}

	public static boolean containsBean(String name) {
		return applicationContext.containsBean(name);
	}

	public static boolean isSingleton(String name) {
		return applicationContext.isSingleton(name);
	}

	public static Class<? extends Object> getType(String name) {
		return applicationContext.getType(name);
	}


	/**
	 * 注意 bean name默认 = 类名(首字母小写)
	 * 例如: A8sClusterDao = getBean("k8sClusterDao")
	 * @param name
	 * @return
	 * @throws BeansException
	 */
	public static Object getBean(String name) throws BeansException {
		return applicationContext.getBean(name);
	}

	/**
	 * 根据类名获取到bean
	 * @param <T>
	 * @param clazz
	 * @return
	 * @throws BeansException
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBeanByName(Class<T> clazz, String subClassName) throws BeansException {
		try {
			char[] cs=clazz.getSimpleName().toCharArray();
			cs[0] += 32;//首字母大写到小写
			return (T) applicationContext.getBean(StringUtils.isNotBlank(subClassName)? subClassName:String.valueOf(cs));
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}